// @author: caoshi
// @date: 2021/5/25 8:19
package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

func main() {

	router := gin.Default()
	router.GET("/", func(c *gin.Context) {
		fmt.Println("开始处理get请求")
		c.String(200, "hello")
	})

	// 1. 获取路径中的参数
	// 此规则能够匹配/user/john这种格式，但不能匹配/user/ 或 /user
	router.GET("/user/:name", func(ctx *gin.Context) {
		name := ctx.Param("name")
		fmt.Println("name = ", name)
		ctx.String(http.StatusOK, "Hello %s", name)
	})

	// http://localhost:8080/user/zhangsan/edit
	router.GET("/user/:name/*action", func(ctx *gin.Context) {
		name := ctx.Param("name")
		action := ctx.Param("action")
		respMsg := name + "--" + action
		fmt.Println("name = ", name)
		fmt.Println("action = ", action) // /edit
		ctx.String(http.StatusOK, respMsg)
	})

	// 2. 获取Get参数
	router.GET("/query", func(ctx *gin.Context) {
		id := ctx.DefaultQuery("id", "")
		username := ctx.DefaultQuery("username", "")
		id = ctx.Query("id")
		username = ctx.Query("username")
		fmt.Printf("id = %s, username = %s\n", id, username)
		ctx.String(http.StatusOK, "Hello %s %s", id, username)
	})

	// 3. 获取POST 参数
	router.POST("/save", func(ctx *gin.Context) {
		name := ctx.PostForm("name")
		age := ctx.PostForm("age")
		addr := ctx.PostForm("addr")
		sex := ctx.DefaultPostForm("sex", "man")

		fmt.Println(name, "--", age, "--", addr, "--", sex)

		ctx.JSON(http.StatusOK, gin.H{
			"name": name,
			"age":  age,
			"addr": addr,
			"sex":  sex,
		})
	})

	// 4. Get + Post 混合
	router.POST("/post", func(ctx *gin.Context) {
		id := ctx.Query("id")
		page := ctx.DefaultQuery("page", "0")
		name := ctx.PostForm("name")
		message := ctx.PostForm("message")

		fmt.Printf("id: %s; page: %s; name: %s; message: %s \n", id, page, name, message)
	})

	_ = router.Run(":8080")

}
